﻿using Caltech.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Caltech.Results;
using CaltechSoft.Service.CommandService;
using ServiceModel = CaltechSoft.Service.DBCommand;
using AutoMapper;
using CaltechSoft.Service.ReportService;
using CaltechSoft.Service.SearchCriteria;
using System.Security.Claims;
using Caltech.Service.Common;
using Caltech.Extensions;
using CaltechSoft.Service.EntityFW.Entity;
using CaltechSoft.Service.Repositories;

namespace Caltech.Controllers
{
    public class TransactionController : ApiController
    {
        private readonly ICertificateCommandService _certificateCommandService;
        private readonly ICertificateReportService _certificateReportService;
        public IRepository<Customer> _customerRepository { get; private set; }

        public TransactionController(ICertificateCommandService certificateCommandService
            , ICertificateReportService certificateReportService
            )
        {
            _certificateCommandService = certificateCommandService;
            _certificateReportService = certificateReportService;
            _customerRepository = new BaseRepository<Customer>();
        }

        // GET api/<controller>
        [HasAccess(Areas.CertificateView)]
        public IHttpActionResult Get(string customerName = "", int? customerId = null, string serialNumber = null, string certificateNumber = null, string modelNumber = null, string username = null, string workOrderNo = null)
        {
            var pageSize = Convert.ToInt32(Request.GetQueryNameValuePairs().FirstOrDefault(n => n.Key == "count").Value);
            var pageIndex = Convert.ToInt32(Request.GetQueryNameValuePairs().FirstOrDefault(n => n.Key == "page").Value) - 1;

            if (!Utils.HasAccess(Areas.CertificateView))
            {
                var logonUsername = User.Identity.GetUserName();

                var customer = _customerRepository.DbSet().FirstOrDefault(x => x.LoginUsername == logonUsername);

                if (customer != null)
                {
                    customerId = customer.Id;
                }
                else
                {
                    return BadRequest("This user has no associated customer to view certificates");
                }
            }

            var searchCriteria = new CertificateSearchCriteria()
            {
                CustomerName = customerName,
                CustomerId = customerId,
                SerialNumber = serialNumber,
                CertificateNumber = certificateNumber,
                ModelNumber = modelNumber,
                WorkOrderNo = workOrderNo,
                Username = username
            };

            var result = _certificateReportService.Search(searchCriteria, pageSize, pageIndex);


            return Request.CreateSearchResult<TransactionListItemModel>(result.Items.Select(x => new TransactionListItemModel()
                {
                    Id = x.CertificateId,
                    Name = x.CustomerName,
                    Description = x.Description,
                    CalibrationDate = x.CalibrationDate,
                    CertificateNo = x.CertificateNo,
                    Manufacturer = x.Manufacturer,
                    SerialNumber = x.SerialNumber
                }), result.Count);
        }

        [HasAccess(Areas.CertificateView)]
        public IHttpActionResult Get(int id)
        {
            var result = _certificateReportService.SearchById(id);
            return Ok(result);
        }

        [HasAccess(Areas.CertificateCreate)]
        public int Post(CertificateModel model)
        {
            var createModel = Mapper.Map<CertificateModel, ServiceModel.CreateNewCertificateCommand>(model);
            if (createModel.CertificateId > 0)
            {
                return _certificateCommandService.UpdateCertificate(createModel.CertificateId.Value, createModel);
            }
            else
            {
                return _certificateCommandService.CreateNewCertificate(createModel);
            }

        }

        // PUT api/<controller>/5
        [HasAccess(Areas.CertificateEdit)]
        public void Put(int id, CertificateModel model)
        {
            var createModel = Mapper.Map<CertificateModel, ServiceModel.CreateNewCertificateCommand>(model);
            _certificateCommandService.UpdateCertificate(id, createModel);
        }

        // DELETE api/<controller>/5
        [HasAccess(Areas.CertificateDelete)]
        public void Delete(int id)
        {
            _certificateCommandService.Delete(id);
        }
    }
}